from django.shortcuts import render
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView, ListCreateAPIView, UpdateAPIView, \
    GenericAPIView
from rest_framework.response import Response
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.models import Area
# Create your views here.
from areas.serializers import AreaSerializer, AddressSerializers

# 查询所有省信息
from users.models import Address


class AreaView(CacheResponseMixin, ListAPIView):
    # 查询所有省信息
    queryset = Area.objects.filter(parent=None)
    # 指定返回序列化器
    serializer_class = AreaSerializer


# 查询所有市信息和区县信息
class AreasView(CacheResponseMixin, ListAPIView):
    # 查询所有市信息和区县信息
    # queryset = Area.objects.filter(parent_id=pk)
    # 指定返回序列化器
    serializer_class = AreaSerializer

    def get_queryset(self):
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)

    # @cache_response()
    # def get(self):


# 地址类视图
class AddressView(ListCreateAPIView, UpdateAPIView):
    serializer_class = AddressSerializers

    # queryset = Address.objects.filter(user)

    # 对获取地址信息和获取默认地址进行设置
    def get(self, request, *args, **kwargs):
        # 获取地址信息
        address = self.get_queryset()
        default_address_id = request.user.default_address_id
        # 获取默认地址，序列化返回
        ser = self.get_serializer(address, many=True)
        return Response({'default_address_id': default_address_id, 'address': ser.data})

    def get_queryset(self):
        return Address.objects.filter(user=self.request.user, is_deleted=False)

    def delete(self, request, pk):
        address = self.get_object()
        address.is_deleted = True
        address.save()
        return Response({'message': 'ok'})


# 默认地址类视图
class StatusView(GenericAPIView):

    def put(self, request, pk):
        user = request.user

        user.default_address_id = pk

        user.save()

        address = Address.objects.get(id=pk)

        ser = AddressSerializers(address)

        return Response(ser.data)
